package cn.com.dcsgo.permission;

import cn.com.dcsgo.constants.CoreConstant;
import cn.com.dcsgo.enums.ResultEnums;
import cn.com.dcsgo.exception.BusinessException;
import cn.com.dcsgo.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义权限注解处理器
 * 优先级较高，先执行
 *
 * @author Dcsgo
 * @since 4/6/2025 上午 8:51
 */
@Slf4j
@Aspect
@Order(0)
@Component
public class MyPermissionAspect {
    /**
     * 权限校验处理，权限集合中的所有权限均没有就抛异常
     *
     * @param myPermission 权限校验注解
     */
    @Before("@annotation(myPermission)")
    public void authPermission(MyPermission myPermission) {
        log.debug("权限校验中");
        List<String> requiredPermissions = Arrays.stream(myPermission.value()).toList();
        Object attribute = ServletUtils.getSession().getAttribute(CoreConstant.PERMISSIONS_KEY);
        List<String> hasPermissions = (List<String>) attribute;

        // 拥有的权限为空直接不允许访问
        if (CollectionUtils.isEmpty(hasPermissions)) {
            throw new BusinessException(ResultEnums.USER_NOT_ALLOW_ACCESS);
        }

        // 如果校验所有权限
        if (myPermission.verifyAll()) {
            if (!hasPermissions.containsAll(requiredPermissions)) {
                throw new BusinessException(ResultEnums.USER_NOT_ALLOW_ACCESS);
            }
        } else {
            // 校验至少拥有一个需要校验的权限
            boolean flag = false;
            for (String p : hasPermissions) {
                if (requiredPermissions.contains(p)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                throw new BusinessException(ResultEnums.USER_NOT_ALLOW_ACCESS);
            }
        }
    }
}
